package com.company;

import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Created by Administrator on 2018/11/8.
 */
public class EncryptUtil {
    private static SecretKeySpec AES_PASSWORD;
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法

    /**
     * AES 加密操作
     * @param content 待加密内容
     * @param key 加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content,String key) {
        if(StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return new BASE64Encoder().encode(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return content;
    }

    /**
     * AES 解密操作
     * @param content 解密的内容字符串
     * @param key 解密的密钥
     * @return
     */
    public static String decrypt(String content,String key) {
        if(StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            byte[] base64Data = new BASE64Decoder().decodeBuffer(content);//先用base64解密
            byte[] original = cipher.doFinal(base64Data);
            String originalString = new String(original, StandardCharsets.UTF_8);
            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return content;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) throws Exception {
        if(AES_PASSWORD !=null){
            return AES_PASSWORD;
        }
        try {  //返回生成指定算法密钥生成器的 KeyGenerator 对象
            byte[] keyBytes = Arrays.copyOf(key.getBytes("ASCII"), 16);
            AES_PASSWORD =new SecretKeySpec(keyBytes, KEY_ALGORITHM);// 转换为AES专用密钥
            return AES_PASSWORD;
        } catch (Exception ex) {
            throw new Exception("加密秘钥失败");
        }
    }
}
